﻿using AmazonMODEL;
using MarketplaceWebService.Model;
using MODEL;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace SysController
{
    /// <summary>
    /// 1.0 报表
    /// </summary>
    public static partial class ReportsController
    {
        #region  2015-11-03 提交请求报告申请 + static ReportsInfo RequestReport(AppKey appkey, ReportsInfo model, ReportType type)
        /// <summary>
        /// 2015-11-03 提交请求报告申请
        /// </summary>
        /// <param name="appkey">授权信息</param>
        /// <param name="model">带有AccountInfoID</param>
        /// <param name="type">报告类型</param>
        /// <returns></returns>
        public static ReportsInfo RequestReport(AppKey appkey, ReportsInfo model, string reportType)
        {
            RequestReportRequest request = new RequestReportRequest()
            {
                Merchant = appkey.MerchantCode,
                MarketplaceIdList = new IdList() { Id = new List<string>() { appkey.MarketplaceCode} },
                ReportType = reportType,
            };
            if (reportType == ReportType._GET_FLAT_FILE_OPEN_LISTINGS_DATA_.ToString())
            {
                request.StartDate = DateTime.Now.AddHours(-8);
                request.EndDate = DateTime.Now;
            }
            try
            {
                RequestReportResponse response = HelperController.RegisterFeedsService(appkey).RequestReport(request);
                ReportRequestInfo info = response.RequestReportResult.ReportRequestInfo;
                if (response.RequestReportResult.IsSetReportRequestInfo())
                {
                    model.ReportRequestId = info.ReportRequestId;
                    model.GeneratedReportId = info.GeneratedReportId;
                    model.ReportProcessingStatus = info.ReportProcessingStatus;
                    model.ReportType = info.ReportType;
                    model.SubmittedDate = info.SubmittedDate.ToString();
                    model.StartDate = info.StartDate.ToString();
                    model.EndDate = info.EndDate.ToString();
                    model.CreateUser = "RequestReport";
                    model.CreateTime = DateTime.Now;
                    model.IsDel = false;
                }
            }
            catch (Exception)
            {
                model = null;
            }
            return model;
        }
        #endregion

        #region  2015-11-03 获取请求报告申请状态 + static List<ReportsInfo> GetReportRequestList(AppKey appkey, List<ReportsInfo> list, ReportType type)
        /// <summary>
        /// 2015-11-03 获取请求报告申请状态
        /// </summary>
        /// <param name="appkey">授权信息</param>
        /// <param name="list">请求报告信息</param>
        /// <param name="type">报告类型</param>
        /// <returns></returns>
        public static List<ReportsInfo> GetReportRequestList(AppKey appkey, List<ReportsInfo> list, string reportType)
        {
            GetReportRequestListRequest request = new GetReportRequestListRequest()
            {
                Marketplace = appkey.MarketplaceCode,
                Merchant = appkey.MerchantCode,
                ReportTypeList = new TypeList() { Type = new List<string>() { reportType } },
                ReportRequestIdList = new IdList() { Id = new List<string>() },
                ReportProcessingStatusList = new StatusList() { Status = new List<string>() { "_DONE_" } },
                MaxCount = 100
            };
            request.ReportRequestIdList.Id = list.Select(s => s.ReportRequestId).ToList();

            try
            {
                GetReportRequestListResponse response = HelperController.RegisterFeedsService(appkey).GetReportRequestList(request);
                if (response.GetReportRequestListResult.IsSetReportRequestInfo())
                {
                    List<ReportRequestInfo> listR = response.GetReportRequestListResult.ReportRequestInfo;
                    List<ReportsInfo> ls = new List<ReportsInfo>();
                    foreach (var item in listR)
                    {
                        ReportsInfo model = list.Where(s => s.ReportRequestId == item.ReportRequestId).FirstOrDefault();
                        if (model == null)
                            continue;
                        model.ReportProcessingStatus = item.ReportProcessingStatus;
                        model.ReportRequestId = item.ReportRequestId;
                        model.ReportType = item.ReportType;
                        model.SubmittedDate = item.SubmittedDate.ToString();
                        model.StartDate = item.StartDate.ToString();
                        model.EndDate = item.EndDate.ToString();
                        model.GeneratedReportId = item.GeneratedReportId;
                        model.UpdateUser = "ReportRequestStatus";
                        model.UpdateTime = DateTime.Now;
                        model.IsDel = false;

                        ls.Add(model);
                    }
                    return ls;
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
        }
        #endregion

        #region 2015-11-04 报告结果 + static ReportsInfo GetReport(AppKey appkey, ReportsInfo model)
        /// <summary>
        /// 2015-11-04 报告下载
        /// </summary>
        /// <param name="appkey"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public static ReportsInfo GetReport(AppKey appkey, ReportsInfo model)
        {
            
            string path = System.Configuration.ConfigurationManager.AppSettings["ReportsFilePath"];
            GetReportRequest request = new GetReportRequest()
            {
                Marketplace = appkey.MarketplaceCode,
                Merchant = appkey.MerchantCode,
                Report = File.Open(string.Format(@"{0}\{1}.txt", path, model.GeneratedReportId), FileMode.OpenOrCreate, FileAccess.ReadWrite),
                ReportId = model.GeneratedReportId
            };
            try
            { 
                GetReportResponse response = HelperController.RegisterFeedsService(appkey).GetReport(request);
                request.Report.Close();
                using (StreamReader reader = File.OpenText(string.Format(@"{0}\{1}.txt", path, model.GeneratedReportId)))
                {
                    model.ResultData = reader.ReadToEnd();
                    reader.Dispose();
                    reader.Close();
                }
            }
            catch (Exception ex)
            {
                SysCommon.Log.Log.Write(JsonConvert.SerializeObject(ex));
            } 
            return model;
        }
        #endregion
    }
}
